package com.shelpe.services.auth.service;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.lang.math.NumberUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;

import com.shelpe.services.auth.entity.AuthInfo;
import com.shelpe.services.auth.entity.Users;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

@Setter
@Slf4j
public class SandboxTokenService implements TokenService {

	private JdbcTemplate template;
	
	private final static String SQL_SELECT = "access_token, taobao_user_id, taobao_user_nick";
	private final static String SQL_BY_NICK = "select " + SQL_SELECT + " from oauth where taobao_user_nick = ? order by taobao_user_id desc limit 1";
	private final static String SQL_BY_ID = "select " + SQL_SELECT + " from oauth where taobao_user_id = ?";
	
	@Override
	public UserInfo getToken(String nick) {
		AuthInfo info = this.template.query(SQL_BY_NICK, new ResultSetExtractor<AuthInfo>(){

			@Override
			public AuthInfo extractData(ResultSet rs) throws SQLException, DataAccessException {
				return toAuthInfo(rs);
			}
			
		}, nick);
		
		UserInfo ui = new UserInfo();
		ui.setAuth(info);
		if(info != null){
			ui.setUser(new Users());
			ui.getUser().setUserId(NumberUtils.toLong(info.getTaobaoUserId()));
		}
		return ui;
	}

	@Override
	public UserInfo getToken(long userId) {
		AuthInfo info = this.template.query(SQL_BY_ID, new ResultSetExtractor<AuthInfo>(){

			@Override
			public AuthInfo extractData(ResultSet rs) throws SQLException, DataAccessException {
				return toAuthInfo(rs);
			}
			
		}, userId);
		
		UserInfo ui = new UserInfo();
		ui.setAuth(info);
		ui.setUser(new Users());
		ui.getUser().setUserId(userId);
		return ui;
	}

	
	private AuthInfo toAuthInfo(ResultSet rs){
		AuthInfo info = null;
		if(rs != null){
			info = new AuthInfo();
			try {
				if(rs.first()){
					info.setAccessToken(rs.getString("access_token"));
					info.setTaobaoUserId(rs.getString("taobao_user_id"));
				}
			} catch (SQLException e) {
				log.error("SQLException: {}", e);
			}
		}
		return info;
	}

}
